import React, { useEffect, useMemo, useState } from 'react'
import Taro,{useDidShow} from '@tarojs/taro'
import {View, Image, Text,ScrollView} from '@tarojs/components'
import './index.scss'
import { AtActionSheet } from 'taro-ui'
import "taro-ui/dist/style/components/action-sheet.scss";
import { RoundNum } from '@/utils/helper'
import InputNumber from '@/components/InputNumber'

export default function Goods() {
  let capsule = {}
  if(process.env.TARO_ENV === 'weapp') capsule = Taro.getMenuButtonBoundingClientRect()
  const [curCate,setCurCate] = useState()
  const [curGoods,setCurGoods] = useState()
  const [suggestList,setsuggestList] = useState([])
  const [goodsList,setGoodsList] = useState([])
  const [distanceList,setDistanceList] = useState([])
  const [cinemaInfo,setCinemaInfo] = useState({})
  const [showCart,setShowCart] = useState(false)
  useDidShow(()=>{
    setCinemaInfo(Taro.getStorageSync('selectMerchant'))
    Taro.$get('/cinema-app/api/v1/cinema/suggest/list',{cinemaId:Taro.getStorageSync('merchantId'),typeId:0}).then(res=>{
      if(res.code == '1') setsuggestList(res.content)
    })
    Taro.showLoading({title:'加载中...'})
    Taro.$get('/cinema-app/api/v1/cinema/goods/list',{cinemaId:Taro.getStorageSync('merchantId')},'1').then(res=>{
      if(res.code == '1'){
        setGoodsList(res.content)
        setCurCate(res.content.findIndex(res=>res.cinemaGoods) || 0)
        //  计算卖品各列表所用高度;解决滚动卖品对应cate
        setTimeout(() => {
          let selectorQuery = Taro.createSelectorQuery()
          let arr = []
          selectorQuery.selectAll('.cate-main-item').boundingClientRect(function(rects) {
            rects.forEach(function(rect) {
              arr.push(rect.top)
            })
            setDistanceList(arr)
          }).exec()
        }, 500);
      }
    })
  })
  const calcPrice = useMemo(()=>{
    let price = 0
    goodsList.map(res=>{
      res.cinemaGoods?.map(ret=>{
        if(ret.goodsCount > 0){
          price += (ret.goodsPrice * +ret.goodsCount)
        }
      })
    })
    return RoundNum(price) || 0
  },[goodsList])
  let calcNum = useMemo(()=>{
    let num = 0;
    goodsList.map(res=>{
      res.cinemaGoods?.map(ret=>{
        if(ret.goodsCount > 0){
          num += 1
        }
      })
    })
    return num || 0
  },[goodsList])
  let timer = ''

  const handleSettle = e=>{  ///  点击去结算
    Taro.verifyLogin()
    if(calcNum < 1) return;
    let data = {
      cinemaId:Taro.getStorageSync('merchantId'),
      goodsList:[]
    }
    goodsList.map(res=>{
      res.cinemaGoods?.map(ret=>{
        if(ret.goodsCount > 0){
          data.goodsList.push({goodsCount:ret.goodsCount,goodsId:ret.id})
        }
      })
    })
    Taro.showLoading({title:'加载中...'})
    Taro.$post('/cinema-app/api/v1/order/create',data,'1').then(res=>{
      if(res.code == '1'){
        Taro.navigateTo({
          url:`/mainPages/goods-confirm/index?id=${res.content.id}`
        })
      }else{
        Taro.$toast(res.message)
      }
    })
  }
  return (
    <View className='goods'>
      <View className="goods-nav-bar" style={{paddingTop:capsule.top+'PX'}}>
        <View className="box-flex" style={{minHeight: capsule.height+'px'}} onClick={()=>{
          Taro.navigateTo({
            url:'/mainPages/select-cinema/index'
          })
        }}>
          {cinemaInfo.cinemaNickName || "请选择影院"}
          <Text className='at-icon at-icon-chevron-down' style={{marginLeft:4}}></Text>
          {cinemaInfo.distance?<View className="distance">距离您 {cinemaInfo.distance}</View>:null}
        </View>
      </View>
      {suggestList?.length?
      <View className="goods-list not-bar">
        {suggestList.map(res=>{
          return <View className="list-item" key={res}>
            <View className='item-icon'>热销</View>
            <View className="item-img">
              <Image src={res.imageUrl} lazyLoad className='img' />
              <View className="item-h2">{res.goodsNickName}</View>
            </View>
            <View className="item-info">
              <View className="info-price"><Text style={{fontSize:'12px'}}>￥</Text>{res.goodsPrice}</View>
              {/* <View className="info-del">￥{res.goodsPrice}</View> */}
              <Image src={require('@/images/common/InputNumber.svg')} onClick={()=>{
                goodsList?.map(ret=>{
                  ret.cinemaGoods?.map(item=>{
                    if(item.id == res.id){
                      item.goodsCount >= 0? item.goodsCount++ : item.goodsCount = 1
                      const arr = [...goodsList]
                      setGoodsList(arr)
                    }
                  })
                })
              }} mode='widthFix' style={{width:'24px',height:'24px',marginLeft: 'auto'}} />
            </View>
          </View>
        })}
      </View>:null}

      {goodsList?.length?
      <View className="goods-cate">
        <ScrollView scrollIntoView={`cate${curCate}`} showScrollbar={false} scrollY className={`cate-list ${suggestList.length?'':'auto-height'}`}>
          {goodsList?.map((res,idx)=>{
            let num = 0;
            return <View id={`cate${idx}`} className={`list-item ${curCate == idx?'active':''}`} key={res} onClick={()=>{
              setCurCate(idx);setCurGoods(idx);
            }}>
              {res.fileUrl?.includes('https')?<Image lazyLoad src={res.fileUrl} mode='widthFix' style={{width:'36px',height:'36px'}} />:null}
              <View className='dot'>{res.className}</View>
              {res.cinemaGoods?.map(item=>{
                if(item.goodsCount > 0){
                  num += item.goodsCount
                }
                return num > 0?<Text className='item-badge'>{num}</Text>:null
              })}
            </View>
          })}
        </ScrollView>
        <ScrollView enablePassive enhanced showScrollbar={false} scrollY className={`cate-main ${suggestList.length?'':'auto-height'}`} scrollIntoView={`item${curGoods}`} onScroll={e=>{
				  // 防抖
          if(timer){
            clearTimeout(timer)
          }
          timer = setTimeout(()=>{
            let scrollTop = e.detail.scrollTop + (distanceList[0] + 2)
            const index = distanceList.findIndex(it=>it >= scrollTop)-1
            console.log(index,scrollTop,distanceList)
            setCurCate(index>=0?index:distanceList.length-1)
          },200)
        }}>
          {goodsList.map((res,idx)=>{
            return <View id={`item${idx}`} className='cate-main-item'>
            {res.cinemaGoods?.length?
            <View className="main-title" key={res.id}>
              <Image src={require('@/images/common/title-icon.svg')} mode='widthFix' style={{width:'16px',height:'16px'}} />
              <Text style={{margin:'0 5px'}}>{res.className}</Text>
              <Image src={require('@/images/common/title-icon.svg')} mode='widthFix' style={{width:'16px',height:'16px',transform: 'rotate(180deg)'}} />
            </View>:null}
            <View className="main-list">
            {res.cinemaGoods?.map(ret=>{
              return <View className="list-item" key={ret.id}>
                <Image src={ret.imageUrl} lazyLoad className='item-img' />
                <View className="item-info">
                  <View className="info-h2 dot2">{ret.goodsNickName}</View>
                  {ret.goodsDesc?<View className="info-sub-title dot2">{ret.goodsDesc}</View>:null}
                  {ret.goodsClassificationName?
                  <View className="info-span">
                    <Text className='span'>{ret.goodsClassificationName}</Text>
                  </View>:null}
                  <View className="info-price">
                    <View>
                      <View className="box-flex">
                        <View className="price-total"><Text style={{fontSize:'12px'}}>￥</Text>{ret.goodsPrice}</View>
                        {/* <Text className='price-del'>￥42.0</Text> */}
                      </View>
                      {/* <View className="box-flex price-vip">
                        <View className="price-total"><Text style={{fontSize:'12px'}}>￥</Text>25.90</View>
                        会员价
                      </View> */}
                    </View>
                    <InputNumber value={ret.goodsCount} onCut={()=>{
                      ret.goodsCount > 0? ret.goodsCount-- : ret.goodsCount = null
                      const arr = [...goodsList]
                      setGoodsList(arr)
                    }} onAdd={()=>{
                      ret.goodsCount >= 0? ret.goodsCount++ : ret.goodsCount = 1
                      const arr = [...goodsList]
                      setGoodsList(arr)
                    }} />
                  </View>
                </View>
              </View>
            })}
            </View>
            </View>
          })}
        </ScrollView>
        <View className="cate-settle">
          <View className="settle-icon" onClick={()=>{setShowCart(true)}}>
            <Image src={require('@/images/cart.svg')} mode='widthFix' style={{width:24,height:24}}></Image>
            {calcNum>0?<View className="icon-drag">{calcNum}</View>:null}
          </View>
          <View className="settle-price">￥{calcPrice}</View>
          <View className="settle-button" onClick={()=>{handleSettle()}}>选好了</View>
        </View>

        <AtActionSheet isOpened={showCart} onClose={()=>{setShowCart(false)}}>
          <View className='goods-action'>
          <View className="action-header">
            <View className="header-h2">共 {calcNum} 件商品</View>
            <View className="header-clear" onClick={()=>{
              Taro.showModal({
                title:'',
                content:'是否清空购物车',
                confirmText:'清空',
                confirmColor:"#c80f2f",
                success:res=>{
                  if(res.confirm){
                    let arr = [...goodsList]
                    arr.map(res=>{
                      res.cinemaGoods?.map(ret=>{
                        ret.goodsCount = 0
                      })
                    })
                    setGoodsList(arr)
                    setShowCart(false)
                  }
                }
              })
            }}><Image src={require('@/images/common/delete.svg')} style={{width:16,height:16,marginRight:4}} mode='widthFix' /></View>
          </View>
          <View className="action-list">
          {calcNum > 0?goodsList.map((res,idx)=>{
            return <View className="main-list">
            {res.cinemaGoods?.map((ret)=>{
              if(ret.goodsCount > 0){
                return <View className="list-item" key={ret.id}>
                  <View className="item-info">
                    <View className="info-h2 dot2">{ret.goodsNickName}</View>
                  </View>
                  <View className="item-price">
                    <View className="price-total"><Text style={{fontSize:'12px'}}>￥</Text>{ret.goodsPrice}</View>
                    <InputNumber value={ret.goodsCount} onCut={()=>{
                      ret.goodsCount > 0? ret.goodsCount-- : ret.goodsCount = null
                      const arr = [...goodsList]
                      setGoodsList(arr)
                    }} onAdd={()=>{
                      ret.goodsCount >= 0? ret.goodsCount++ : ret.goodsCount = 1
                      const arr = [...goodsList]
                      setGoodsList(arr)
                    }} />
                  </View>
                </View>
              }
            })}
            </View>
          }):<View className='var-empty'>暂无数据</View>}
          </View>
          <View className="cate-settle action-footer">
            <View className="settle-icon" onClick={()=>{setShowCart(true)}}>
              <Image src={require('@/images/cart.svg')} mode='widthFix' style={{width:24,height:24}}></Image>
              {calcNum>0?<View className="icon-drag">{calcNum}</View>:null}
            </View>
            <View className="settle-price">￥{calcPrice}</View>
            <View className="settle-button" onClick={()=>{handleSettle()}}>去结算</View>
          </View>
          </View>
        </AtActionSheet>
      </View>:<View className='var-empty'>暂无数据</View>}
    </View>
  )
}
